package com.home.qh.dao.hibernate;

import java.util.List;

import org.hibernate.criterion.CriteriaSpecification;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Repository;

import com.home.qh.dao.PayingDao;
import com.home.qh.model.Paying;


/**
 * This class interacts with Spring's HibernateTemplate to save/delete and
 * retrieve Role objects.
 *
 * @author <a href="mailto:bwnoll@gmail.com">Bryan Noll</a> 
 */
@Repository
public class PayingDaoHibernate extends GenericDaoHibernate<Paying, Long> implements PayingDao {

    /**
     * Constructor to create a Generics-based version using Role as the entity
     */
    public PayingDaoHibernate() {
        super(Paying.class);
    }

    /**
     * {@inheritDoc}
     */
    public List<Paying> getPayingByCodeAndName(String payingCode, String payingName) {
    	List<Paying> payings = getHibernateTemplate().find("from Paying where name like '%?%'", payingName);
        if (payings.isEmpty()) {
            return null;
        } else {
            return payings;
        }
    }

	public List<Paying> getPayingByPaying(Paying paying, String sort, boolean desc, int startResult, int maxResults) {
        DetachedCriteria criteria = DetachedCriteria.forClass(Paying.class);

        if (paying.getCode() != null) {
        	criteria.add(Restrictions.or(Restrictions.eq("code", paying.getCode()), Restrictions.eq("name", paying.getName())));
		}

        if(sort != null && !"".equalsIgnoreCase(sort)) {
            if(desc) criteria.addOrder(Order.desc(sort));
            else criteria.addOrder(Order.asc(sort));
        }

        criteria.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY);
        
        return getHibernateTemplate().findByCriteria(criteria, startResult, maxResults);
	}

   
}
